package com.itboye.textileexpres.top;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.itboye.textileexpes.presenter.CategoryPresenter;
import com.itboye.textileexpres.R;
import com.itboye.textileexpres.base.BaseActivity;
import com.itboye.textileexpres.base.ResultEntity;
import com.itboye.textileexpres.base.SpPublicParams;
import com.itboye.textileexpres.main.MainActivity;
import com.itboye.textileexpres.util.CameraPopupWindow;
import com.itboye.textileexpres.util.DebugLog;
import com.itboye.textileexpres.util.ImageCompress;
import com.itboye.textileexpres.util.ImageCompressAndUpload;
import com.itboye.textileexpres.util.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.textileexpres.util.PhotoSelectFragment;
import com.itboye.textileexpres.util.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.textileexpres.util.SPUtils;
import com.itboye.textileexpres.util.XImageLoader;
import com.itboye.textileexpres.widget.ImageDialog;

public class ActivityCarmarSearch extends BaseActivity implements
		OnClickListener, Observer, TextWatcher {
	TextView next_one, title;
	ImageView back;
	ImageView img_other;
	Button btn_send;
	EditText edit;
	EditText call_way;
	// LinearLayout edit_lin;
	ArrayList<String> uploadedUrl = new ArrayList<String>();
	protected CameraPopupWindow mCameraPopupWindow;
	private ImageView add;
	ViewGroup imgContainer;
	CategoryPresenter presenter;
	Handler handler;
	View popView;

	@Override
	public int initView() {
		// TODO Auto-generated method stub
		return R.layout.activity_img_search;
	}

	@Override
	public void onMyCreate() {
		// TODO Auto-generated method stub
		btn_send.setEnabled(false);
		img_other.setVisibility(View.GONE);
		title.setText("照片搜索");
		presenter = new CategoryPresenter(this);
		handler = new Handler();

		if (imgContainer.getChildCount() < 3) {
			add.setVisibility(View.VISIBLE);
		} else if (imgContainer.getChildCount() == 3) {
			add.setVisibility(View.GONE);
		}

		edit.addTextChangedListener(this);
		btn_send.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				onuploadedUrl();
			}
		});
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.back:
			uploadedUrl.clear();
			// showDialog();
			// onuploadedUrl();
			finish();
			break;
		case R.id.add:
			mCameraPopupWindow = new CameraPopupWindow(
					ActivityCarmarSearch.this, onclicklister);
			mCameraPopupWindow.showAtLocation(
					ActivityCarmarSearch.this.findViewById(R.id.add),
					Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			break;

		default:
			break;
		}
	}

	public List<String> path = new ArrayList<String>();
	protected int countImg;
	private StringBuffer imgId = new StringBuffer();

	public void onuploadedUrl() {
		uploadedUrl.clear();

		if (imgContainer.getChildCount() == 1) {
			sendImageIdToServer();
		} else {
			// if (wait == null) {
			showProgressDialog("图片上传中", true);
			for (int i = 0; i < imgContainer.getChildCount() - 1; i++) {

				ImageCompressAndUpload.getInstance().execute(
						(String) imgContainer.getChildAt(i).getTag(),
						new OnUploadlistener() {

							@Override
							public void OnSuccess(String resultData) {
								uploadedUrl.add(resultData);
								DebugLog.v("bytag", resultData);
								if (uploadedUrl.size() == imgContainer
										.getChildCount() - 1) {
									// if (wait != null) {
									// wait.dismiss();
									// }
									System.out.println("resulitjweuriwoe "
											+ resultData);

									sendImageIdToServer();
								}
							}

							@Override
							public void OnError(String resultData) {

							}
						});

			}

		}
	}

	private String strEdittextView;
	private String uid;
	private String phone;

	/**
	 * 照片搜索
	 * 
	 * SSAQ-003078-NBPKY 6etLacUB
	 * 
	 * @param imgIds
	 *            图片id
	 * @param imgPath
	 *            size
	 */
	@SuppressWarnings("unused")
	private void sendImageIdToServer() {
		String img_ids = null;
		if (uploadedUrl.size() > 0) {
			StringBuilder sb = new StringBuilder();
			sb.append(uploadedUrl.get(0));
			for (int i = 1; i < uploadedUrl.size(); i++) {
				sb.append(",").append(uploadedUrl.get(i));
			}

			img_ids = sb.toString();
			System.out.println("KLKLKLKLK" + img_ids);
		}
		strEdittextView = edit.getText().toString().trim();
		if (!strEdittextView.equals("") || strEdittextView != null) {
			uid = (String) SPUtils.get(this, null, SpPublicParams.UID, "");
			phone = call_way.getText() + "";
			presenter.onPhoto(img_ids, uid, strEdittextView, phone);
		} else {
			toast("文本内容不能为空！");
		}

	}

	private String picture_name;
	private String fileName;
	private OnClickListener onclicklister = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.open_camera:
				if (imgContainer.getChildCount() > 3) {

					add.setVisibility(View.GONE);
					toast("最多3张");
					return;
				} else {
					add.setVisibility(View.VISIBLE);
				}
				/**
				 * 打开照相机
				 */
				picture_name = android.text.format.DateFormat.format(
						"yyyyMMdd_hhmmss", Calendar.getInstance(Locale.CHINA))
						+ ".jpg";
				File file = new File("/sdcard/Image/");
				file.mkdirs();// 创建文件夹
				fileName = "/sdcard/Image/" + picture_name;
				Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
				intent.putExtra(MediaStore.EXTRA_OUTPUT,
						Uri.fromFile(new File(fileName)));
				startActivityForResult(intent, Activity.DEFAULT_KEYS_DIALER);
				break;
			case R.id.pick_image:
				new PhotoSelectFragment(new PhotoSelect(),
						3 - imgContainer.getChildCount() + 1).show(
						getSupportFragmentManager(), null);
				break;
			case R.id.img:
				break;
			default:
				break;
			}
		}
	};
	public ArrayList<String> imgPath = new ArrayList<String>();
	int index = -1, index2 = -1;

	class PhotoSelect implements PhotoSelectListener {

		@Override
		public void onPhotoSelectFinish(List<String> paths) {
			for (String string : paths) {
				index++;
				imgPath.add(string);
				final View v = LayoutInflater.from(getApplicationContext())
						.inflate(R.layout.item_shear_news, null);

				v.setLayoutParams(new LayoutParams((int) getResources()
						.getDimension(R.dimen.tizie_imageview_width),
						LayoutParams.MATCH_PARENT));
				Bitmap bit = BitmapFactory.decodeFile(string);
				int degree = ImageCompress.readPictureDegree(string);
				if (degree <= 0) {

				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// // 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);

				}
				String sdStatus = Environment.getExternalStorageState();
				if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
					Log.i("TestFile",
							"SD card is not avaiable/writeable right now.");
					return;
				}
				FileOutputStream b = null;
				try {
					b = new FileOutputStream(string);
					bit.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				} finally {
					try {
						b.flush();
						b.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}

				if (imgContainer.getChildCount() >= 3) {
					add.setVisibility(View.GONE);
				} else
					add.setVisibility(View.VISIBLE);
				XImageLoader.load("file://" + string,
						(ImageView) v.findViewById(R.id.img));
				v.setTag(string);
				v.setTag(R.id.tabs, index);
				imgContainer.addView(v, imgContainer.getChildCount() - 1);
				mCameraPopupWindow.dismiss();

			}
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
			if (resultCode == RESULT_OK) {
				Bitmap bit = BitmapFactory.decodeFile(fileName);
				int degree = ImageCompress.readPictureDegree(fileName);
				if (degree <= 0) {
					// show_Image.setImageBitmap(bm);
				} else {
					// 创建操作图片是用的matrix对象
					Matrix matrix = new Matrix();
					// 旋转图片动作
					matrix.postRotate(degree);
					// 创建新图片
					bit = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(),
							bit.getHeight(), matrix, true);
				}
				int num = 0;
				saveImage(bit, new File(fileName));
				// content.insertBitmap(fileName);

			} else {
				toast("拍照取消");
			}
			mCameraPopupWindow.dismiss();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void saveImage(Bitmap data, File fileName) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { // 检测sd是否可用
			Log.i("TestFile", "SD card is not avaiable/writeable right now.");
			return;
		}
		FileOutputStream b = null;
		try {
			b = new FileOutputStream(fileName);
			data.compress(Bitmap.CompressFormat.JPEG, 100, b);// 把数据写入文件
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			final View v = LayoutInflater.from(getApplicationContext())
					.inflate(R.layout.item_shear_news, null);

			v.setLayoutParams(new LayoutParams((int) getResources()
					.getDimension(R.dimen.tizie_imageview_width),
					LayoutParams.MATCH_PARENT));
			v.setTag(this.fileName);
			((ImageView) v.findViewById(R.id.img)).setImageBitmap(data);
			imgContainer.addView(v, imgContainer.getChildCount() - 1);
		} catch (Exception e) {
			Log.e("error", e.getMessage());
		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub

		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == CategoryPresenter.Photo_success) {
				if (getIntent().getStringExtra("from").equals("top")) {

				} else {
					showDialog();
				}

				try {
					closeProgressDialog();
				} catch (Exception e) {
					// TODO: handle exception
				}

				toast("" + entity.getData());
			}
		}
	}

	void showDialog() {
		// View view = LayoutInflater.from(ActivityCarmarSearch.this).inflate(
		// R.layout.image_search_dialog, null);
		// popView=new pop
		ImageDialog.Builder builder = new ImageDialog.Builder(
				ActivityCarmarSearch.this);
		builder.Create().show();
		builder.setYes("确定", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub

				if ("search".equals(ImageDialog.type)) {
					Intent intent = new Intent(ActivityCarmarSearch.this,
							ActivityTypeTwoGoods.class);
					startActivity(intent);
				} else {
					Intent intent = new Intent(ActivityCarmarSearch.this,
							MainActivity.class);
					startActivity(intent);
				}
				dialog.dismiss();
				finish();
			}
		});

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub
		if (edit.getText().toString().length() > 0) {
			btn_send.setEnabled(true);
		} else {
			btn_send.setEnabled(false);
		}
	}
}
